﻿using UnityEngine;
using System.Collections.Generic;
using Room;
using ProtoBuf.Message;
/// <summary>
/// 公会战跑图页面
/// </summary>
namespace UI
{
    public class UIUnionFightRunMap : Page
    {
        public static bool isUnionFightPage;
        public UIUnionFightHeroInfo HeroInfo;
        public UIUnionFightStater StateInfo;
        public UIUnionFightChat ChatInfo;


        #region Pages
        public UIUnionFightOrderPage orderPage;
        public UIUnionFightReviveTips reviveTipPage;
        public UIUnionFightReviveTips deadTipPage;
        public UIUnionFightCombatLog combatLogPage;
        public NPCUIShopPage shopPage;
        public NPCUIBuildingPage buildingPage;
        public UIUnionFightTaskPage taskPage;
        public UIUnionFightBattleResult resultPage;
        public UIUnionFightMapPage bigMapPage;
        public UIUnionFightChatPage chatPage;
        #endregion

        public UILabel unionResLabel;
        public UILabel contributeLabel;
        public UILabel battleScoreLabel;
        public UILabel bagResLabel;
        public GameObject bagFullTip;
        public GameObject orderBtn;//会长可见
        public GameObject levelUpBtn;//会长可见
        public GameObject[] items;
        List<MonoBehaviour> pages = new List<MonoBehaviour>();

        protected override void DoOpen()
        {
            ManagerController.Instance.TownToUnionFight();
            isUnionFightPage = true;
            pages.Add(reviveTipPage);
            pages.Add(combatLogPage);
            pages.Add(shopPage);
            pages.Add(buildingPage);
            pages.Add(taskPage);
            pages.Add(deadTipPage);
            pages.Add(chatPage);
        }
        /// <summary>
        /// 刷新界面
        /// </summary>
        public void Refresh()
        {
            StateInfo.Refresh();
            ChatInfo.Refresh();
            Init();
        }

        void Init()
        {
            HeroInfo.Init();
            StateInfo.Init();
            ChatInfo.Init();
            InfoInit();
        }

        protected override void DoClose()
        {
            ManagerController.Instance.UnionFightToTown();
            isUnionFightPage = false;
            pages.Clear();
        }

        public override void OnForceClose()
        {
            base.OnForceClose();
            isUnionFightPage = false;
            pages.Clear();
        }


        #region 初始化、刷新
        void InfoInit()
        {
            var playerId = StaticData.playerData.playerId;
            if (GetNetData().netActor.players.ContainsKey(playerId))
            {
                var player = GetNetData().netActor.players[playerId];
                RefreshBag(player.items);
                SetResBagNum((int)player.ownRes.resourceNum);
                SetContributionNum((int)player.ownToken);
                SetBattleScore((int)player.ownScore);
                //orderBtn.SetActive(player.unionAuthority != 0);
                //levelUpBtn.SetActive(player.unionAuthority != 0);
            }

            SetUnionResNum(GetNetData().netBattle.GetSelfCampUnionResourseNum());
        }

        //设置道具背包
        public void RefreshBag(List<InstUFItem> list)
        {
            if (list.Count > 5)
                Debug.LogError("空间不足");
            for(int i = 0; i < items.Length; i++)
            {
                var script = items[i].GetComponent<UIUnionFightBagItem>();
                script.ResetBag();
            }
            for (int i = 0; i < list.Count; i++)
            {
                int index = list[i].index;
                var script = items[index].GetComponent<UIUnionFightBagItem>();
                script.SetItem(list[i]);
            }
        }

        public void UseItem(string itemId)
        {
            for (int i = 0; i < items.Length; i++)
            {
                var script = items[i].GetComponent<UIUnionFightBagItem>();
                if(script.isHaveItem && script.item.id == itemId)
                {
                    script.ReduceItem();
                    break;
                }
            }
        }

        public void SetReviveTime(float time,string itemId = "")
        {
            StateInfo.SetReviveTime(time);
            if (!string.IsNullOrEmpty(itemId))
            {
                OpenReviveTipPage(itemId, time);
            }
            else
            {
                deadTipPage.Init(time);
            }
        }

        //设置右下角个人携带的资源
        public void SetResBagNum(int ownNum)
        {
            int maxNum = Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.UnionFightResNum;
            bool isFull = ownNum >= maxNum;
            bagFullTip.SetActive(isFull);
            ownNum = Mathf.Clamp(ownNum, 0, maxNum);
            StaticData.unionFightData.selfResNum = ownNum;
            bagResLabel.text = ownNum + "/" + maxNum;
        }
        //道具复活提示
        public void OpenReviveTipPage(string itemId, float time = 10f)
        {
            int index = 0;
            for(int i = 0; i < items.Length; i++)
            {
                if (items[i].GetComponent<UIUnionFightBagItem>().item.id == itemId)
                {
                    index = i;
                    break;
                }
            }
            reviveTipPage.Init(time,items[index]);
        }

        //战斗结算面板
        public void OpenBattleResultPage(int winCamp, UFFightResult result)
        {
            var self = GetNetData().charactorManager.GetSelfCharactor();
            bool isWin = self.Camp == winCamp;
            resultPage.Init(isWin, result);

            foreach( var page in pages)
            {
                page.gameObject.SetActive(false);
            }
            if(bigMapPage != null)
            {
                bigMapPage.Close();
            }
        }

        //红点推送信息
        public void SetRedState(int index,bool isShow)
        {
            redTips[index].SetActive(isShow);
        }

        public void OpenFightRecordPage(SCUFFightRecord msg)
        {
            combatLogPage.InitView(msg);
        }

        public void OpenBigMapPage()
        {
            bigMapPage.Init();
        }
        #endregion

      

        #region TopBar

        public void SetBattleScore(int score)
        {
            battleScoreLabel.text = score + "";
        }

        public void SetUnionResNum(int num)
        {
            unionResLabel.text = num + "";
        }
        public void SetContributionNum(int num)
        {
            contributeLabel.text = num + "";
        }
        #endregion

        #region 工具
        public static RoomNetUnionFight GetNetData()
        {
            var room = GetRoom();
            if (room != null)
            {
                var net = room.netManager as RoomNetUnionFight;
                return net;
            }

            return null;
        }

        public static RoomUnionFight GetRoom()
        {
            var room = RoomManager.currentRoom as RoomUnionFight;
            return room;
        }

        bool isNeedUpdate;
        void CheckUpdate()
        {
            if(!resultPage.gameObject.activeInHierarchy)
                GetNetData().SendCSUFFightResult();
        }

#if (UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR
        public void OnApplicationPause(bool isPause)
        {
            Debug.LogWarning("pause " + isPause);
            if (isPause)
            {
                isNeedUpdate = true;
            }
            else if(!isPause && isNeedUpdate)
            {
                CheckUpdate();
                isNeedUpdate = false;
            }
        }
#endif
        #endregion
    }
}
